package cn.gailvlun.gll.presentation.emotion

import android.app.Activity
import android.app.Dialog
import android.arch.lifecycle.ViewModelProviders
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import android.view.View
import android.view.ViewTreeObserver
import cn.gailvlun.gll.databinding.ItemEmotionSameListEmotionBinding
import cn.gailvlun.gll.net.GsonUtil
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.emotion.Emotion
import cn.gailvlun.gll.net.emotion.EmotionTag
import cn.gailvlun.gll.net.emotion.EmotionTagReq
import cn.gailvlun.gll.net.emotion.RefreshReq
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.emotion.core.BaseAdapter
import cn.gailvlun.gll.presentation.emotion.core.BaseViewModel
import cn.gailvlun.gll.presentation.emotion.core.ImmersionHeaderActivity
import cn.gailvlun.gll.presentation.emotion.core.ViewModelFactory
import cn.gailvlun.gll.presentation.emotion.edit.EmotionRecordActivity
import cn.gailvlun.gll.presentation.emotion.photo.GalleryActivity
import cn.gailvlun.gll.presentation.emotion.photo.VIEW_NAME_IMAGE
import cn.gailvlun.gll.presentation.emotion.widget.CollapseTextView
import cn.gailvlun.gll.presentation.emotion.widget.DividerDecoration
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.IsEmpty
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.widget.NavigationBarView


const val EMOTION_TAG_ID = "emotion_tag_id"

class EmotionSameListActivity : ImmersionHeaderActivity() {
    private var mEmotionTagId: Int = 0
    private lateinit var mViewModel: EmotionSameListViewModel
    private var mEmotionTag: EmotionTag? = null

    companion object {
        @JvmStatic
        fun openActivity(activity: BaseActivity, emotionTagId: Int) {
            val intent = Intent(activity, EmotionSameListActivity::class.java)
            intent.putExtra(EMOTION_TAG_ID, emotionTagId)
            activity.startActivity(intent)

        }
    }

    override fun initAdapter(): BaseAdapter<*> {
        return EmotionSameListAdapter(mContext)
    }

    override fun initViewModel(): BaseViewModel {
        return ViewModelProviders.of(this, ViewModelFactory.getInstance(mContext, adapter as BaseAdapter<Any>)).get(EmotionSameListViewModel::class.java)
    }

    override fun getSubclassEnum(): SubclassEnum {
        return SubclassEnum.SameList
    }

    override fun initComponent() {
        super.initComponent()
        binding.rvEmotionList.addItemDecoration(DividerDecoration(mContext))
        binding.srl.isEnableRefresh = false
        adapter.setDecorator { holder, position, viewType ->
            val itemBinding = holder.binding
            if (itemBinding is ItemEmotionSameListEmotionBinding) {
                itemBinding.llTextAndImage?.igvEmotionImage?.setOnPhotoClickListener { iv, photos, position ->
                    val options = ActivityOptionsCompat.makeSceneTransitionAnimation(mContext, itemBinding.llTextAndImage.igvEmotionImage, VIEW_NAME_IMAGE + "-" + position)
                    GalleryActivity.openActivity(mContext, java.util.ArrayList(photos), position, null)
                }

                val emotion = adapter.getData()[position] as Emotion
                itemBinding.rlToolBar?.ctvFunction?.setOnClickListener { view -> mViewModel.showFunction(view, emotion) }

                itemBinding.llTextAndImage?.ctvContent?.setOnCollapseTextListener(object : CollapseTextView.OnCollapseTextListener {
                    override fun onCollapseText(view: View) {
                        val r = Rect()
                        binding.rvEmotionList.getChildVisibleRect(itemBinding.getRoot(), r, null)
                        if (r.top < 20) {
                            linearLayoutManager.scrollToPositionWithOffset(position, binding.nbv.height)
                        }
                    }
                })
                itemBinding.getRoot().viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
                    override fun onGlobalLayout() {
                        (itemBinding).ivMostLight.x = randon.nextInt(itemBinding.getRoot().width).toFloat()
                        (itemBinding).ivMostLight.y = randon.nextInt(itemBinding.getRoot().height).toFloat()
                        (itemBinding).ivSecondLight.x = randon1.nextInt(itemBinding.getRoot().width).toFloat()
                        (itemBinding).ivSecondLight.y = randon1.nextInt(itemBinding.getRoot().height).toFloat()
                        (itemBinding).ivLightDark.x = randon2.nextInt(itemBinding.getRoot().width).toFloat()
                        (itemBinding).ivLightDark.y = randon2.nextInt(itemBinding.getRoot().height).toFloat()
                        itemBinding.getRoot().viewTreeObserver.removeOnGlobalLayoutListener(this)
                    }
                })
            }
        }
    }

    override fun onMenuClick(nbv: NavigationBarView) {
        val emotionTagReq = EmotionTagReq()
        if (mEmotionTag != null) {
            emotionTagReq.id = mEmotionTag!!.id
            emotionTagReq.emotionState = mEmotionTag!!.emotionType
            emotionTagReq.title = mEmotionTag!!.title
            emotionTagReq.icon = mEmotionTag!!.icon
            emotionTagReq.isUserCreated = false
            EmotionRecordActivity.openActivity(mContext, emotionTagReq) { activityResult ->
                if (activityResult.resultCode() == Activity.RESULT_OK) {
                    val emotionString = activityResult.data().getStringExtra("extra_emotion_obj")
                    val emotion = GsonUtil.getGson().fromJson<Emotion>(emotionString, Emotion::class.java)
                    binding.rvEmotionList.smoothScrollToPosition(0)
                    adapter.add(1, emotion, EmotionSameListAdapter.Type.CONTENT.ordinal)




                }
            }
        }
    }

    override fun loadData(savedInstanceState: Bundle?) {
        mEmotionTagId = intent.getIntExtra(EMOTION_TAG_ID, 0)
        super.loadData(savedInstanceState)
    }

    private var pd: Dialog? = null
    override fun getData(req: RefreshReq) {
        pd = DialogUtil.showIndeterminate(mContext)
        HttpMethods.getEmotionService()
                .getSameList(req.id,
                        req.direction,
                        mEmotionTagId
                )
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<ListRes<Emotion>>() {
                    override fun onSuccess(response: ListRes<Emotion>) {
                        binding.invalidateAll()
                        binding.srl.isEnableLoadmore = response.isNext
                        if (response.results.size > 0) {
                            val lastIndex = response.results.size - 1
                            req.id = response.results[lastIndex].id
                        }
                        if (req.isLoadMore) {
                            adapter.addAll(response.results, EmotionSameListAdapter.Type.CONTENT.ordinal)
                        } else {
                            binding.invalidateAll()
                            adapter.clear()
                            if (IsEmpty.list(response.results)) {
                                adapter.add(null, EmotionSameListAdapter.Type.EMPTY.ordinal)
                            } else {
                                getEmotionTagCreatorInfo(response.results)

                            }
                        }
                        pd?.dismiss()
                        binding.srl.finishLoadmore(0)
                        binding.srl.finishRefresh(0)
                    }

                    override fun onFailure(errMsg: String, response: ListRes<Emotion>?, code: Int) {
                        pd?.dismiss()
                        DialogUtil.showError(mContext, errMsg)
                        binding.srl.finishLoadmore(0)
                        binding.srl.finishRefresh(0)
                    }
                })
    }

    fun getEmotionTagCreatorInfo(emotionList: List<Emotion>) {
        HttpMethods.getEmotionService()
                .getEmotionTagCreatorInfo(mEmotionTagId)
                .compose(RxUtil.applyScheduler())
                .compose(bindToLifecycle())
                .subscribe(object : HttpSubscriber<EmotionTag>() {
                    override fun onSuccess(response: EmotionTag?) {
                        pd?.dismiss()
                        mEmotionTag = response
                        adapter.add(response, EmotionSameListAdapter.Type.HEADER.ordinal)
                        adapter.addAll(emotionList, EmotionSameListAdapter.Type.CONTENT.ordinal)
                    }

                    override fun onFailure(errMsg: String?, response: EmotionTag?, code: Int) {
                        pd?.dismiss()
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }
}